import { getType } from '@/config/content-type'
import chokidar from 'chokidar'

export function watchFile (p: string, cb: (...args: any[]) => void) {
  return chokidar.watch(p).on('all', (event, path) => {
    if (['change'].includes(event)) {
      if (cb) cb()
    }
  })
}

export interface Item {
  path: string

  type: 'office' | 'image' | 'pdf'

  closed: boolean

  closedCb: () => any
}

const cache = new Map<string, Item[]>()

/**
 * windows下的wps在打开第二个文档的时候，open打开的进程会立马退出，将与第一个进程合并
 * @param path
 * @param closedCb
 */
export function putInCache (path: string, closedCb: () => any) {
  const type = getType(path)
  let items = cache.get(type)
  if (!items) {
    items = []
    cache.set(type, items)
  }
  items.push({
    path,
    type,
    closed: false,
    closedCb
  })
}

export function removeFromCache (path: string) {
  const type = getType(path)
  const items = cache.get(type)
  if (!items) return
  const item = items.find(v => v.path === path)
  if (item) item.closed = true

  const allClosed = !items.some(v => !v.closed)

  if (allClosed) {
    items.forEach(v => {
      if (v.closedCb) v.closedCb()
    })
  }
}
